import cryptoMd5 from "./crypto"
import { showToast ,showLoadingToast,allowMultipleToast,closeToast} from 'vant';
allowMultipleToast()
// const domin = 'https://www.haitunxy.com'
function getConfig(){
  return {
    needSign:true,
    showLoading:true,
    headers:{
      "Content-Type": "application/json"
    } as any
  }
}
type Config = Partial<ReturnType<typeof getConfig>>
export default function request(url:string, method:'GET'|'POST',data?:any, config: Config={}){
  const newConfig = Object.assign(getConfig(),config)
  const cryptoData = newConfig.needSign ? cryptoMd5(data) : data
  closeToast()
  if(method == 'GET'){
    url += '?'+ new URLSearchParams(cryptoData).toString()
  }

  if(newConfig.showLoading){
    showLoadingToast({
      message: '加载中...',
      forbidClick: true,
      duration:0
    });
  }
  const options = {
    headers: newConfig.headers,
    method: method,
    body: JSON.stringify(cryptoData)
  }

  if(method == 'GET'){
    // @ts-ignore
    delete options.body
  }
  return new Promise<any>(async(resolve, reject) => {
    const res = await fetch(url, options)
    const parseRes = await res.json()
    if(newConfig.showLoading){
      closeToast()
    }
    if(parseRes.code === 0){
      resolve(parseRes.data)
    }else{
        if(parseRes.msg && parseRes.code !== 201){
          showToast(parseRes.msg)
        }
      reject(parseRes)
    }
  })
  
}